<script setup>
import Toast from '@vant/weapp/dist/toast/toast';
import newLoading from '@/components/newLoading/index.vue';
import { getCategoryDetail } from '@/api/home'
import { getBackgroundImgTemplates, hairStyleEdit, editImgUpload, getImageByTaskId } from '@/api/painting';
import { imgUploadVerify } from '@/utils/auth'
import { ref } from 'vue';
import { onLoad, onReady } from '@dcloudio/uni-app';


// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 页面参数
const queryParams = ref({
    imageFileUrl: ''
})
// 提交数据
const queryData = ref({
    imageFileUrl: '',
    hairType: '',
})

// tabs列表
const tabsList = ref([])
// 当前选中tab
const activeTab = ref('')

// 发型列表
const hairList = ref({})

// 消耗算力
const expendNum = ref(0)

const loading = ref(false);
const loadingRef = ref(null)
// 任务id
const taskId = ref('经典发型')
// 定时器
let timer = null

// 类型列表scroll-view
const typeListScrollView = ref({})
const scrollLeft = ref(0)


// tabs切换
function tabsChange(e) {
    activeTab.value = e.detail.title
    scrollLeft.value = Math.random() * 0.1

}


// 校验方法
function verifyFn() {
    return new Promise((resolve, reject) => {
        if (!queryParams.value.imageFileUrl) {
            Toast.fail('请上传图片')
            return reject()
        }
        resolve()
    })
}


// 立即生成
async function startFn() {
    await verifyFn()
    loading.value = true
    await editImgUploadFn()
    hairStyleEditFn()
}


// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        res.data.title = queryInfo.value.title
        uni.navigateTo({
            url: `/newEditionDraw/recreationDrawResult/index?data=${JSON.stringify(res.data)}`
        })
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        const errorMessage = res.data?.remark.split('失败原因：')[1]
        Toast.fail(errorMessage);
        loading.value = false
    }
}



// 发型编辑任务提交
async function hairStyleEditFn() {
    try {
        const res = await hairStyleEdit(queryData.value)
        taskId.value = res.data.taskId
        timer = setInterval(() => {
            getImageByTaskIdFn()
        }, 2000);
    } catch (error) {
        loading.value = false
    }
}

// 上传原图
async function editImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await editImgUpload({
                type: 20,
                orgImg: queryParams.value.imageFileUrl
            })
            queryData.value.imageFileUrl = res.orgImgUrl
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }
    })
}


// 相册选择
async function uploadImgFn() {
    const res = await imgUploadVerify()
    queryParams.value.imageFileUrl = res
}

// 发型类型选择
function typeChange(item, i) {
    queryData.value.hairType = item.templateId
    queryData.value.typeName = item.name
    queryData.value.stypeId = item.stypeId
    setTimeout(() => {
        uni.createSelectorQuery().selectAll('.type_item').boundingClientRect(rect => {
            let left = 0
            for (let index = 0; index < i; index++) {
                left += rect[index].width + 10
            }
            scrollLeft.value = left - typeListScrollView.value.width / 2 + rect[i].width - 40
        }).exec()
    }, 100)
}

// 获取发型列表
async function getBackgroundImgTemplatesFn() {
    const res = await getBackgroundImgTemplates(3)
    hairList.value = res.data
    tabsList.value = Object.keys(res.data)
    activeTab.value = tabsList.value[0]
    queryData.value = {
        hairType: res.data[tabsList.value[0]][0].templateId,
        typeName: res.data[tabsList.value[0]][0].name,
        stypeId: res.data[tabsList.value[0]][0].stypeId,
    }
}

// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id)
    queryInfo.value = res.data
    dataConversion()
}


// 数据转换
function dataConversion() {
    queryInfo.value.categoryParam.forEach(item => {
        if (item.title === 'expendNum') {
            expendNum.value = item.data[0].title
        }
    })
}

// 图片预览
function previewImageFn() {
    uni.previewImage({
        urls: [queryParams.value.imageFileUrl],
    });
}

// 加载关闭事件
function loadingClose() {
    clearInterval(timer);
}



onReady(() => {
    uni.createSelectorQuery().select('.typeListScrollView').boundingClientRect(data => {
        typeListScrollView.value = data
    }).exec()
})

onLoad((e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
    }
    getCategoryDetailFn()
    getBackgroundImgTemplatesFn()
})


defineExpose({
    uploadImgFn,
})
</script>

<template>
    <div class='redrawHairstyle'>
        <NavBar>{{ queryInfo?.title }}</NavBar>
        <div class="container">
            <div class="img_box">
                <!--上传按钮-->
                <div v-if="!queryParams.imageFileUrl" class="uploadImgBtn" @click="uploadImgFn">
                    <i class="iconfont ai-icon-xiangcexuanze"></i>
                    相册选择
                </div>
                <!--重新上传-->
                <div v-else class="upload_box" @click.stop="uploadImgFn">
                    <i class="iconfont ai-icon-refresh"></i>
                    重新上传
                </div>

                <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" alt="" class="imgSty" mode="aspectFit"
                    @click="previewImageFn">
            </div>
        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <van-tabs :active="activeTab" title-active-color="var(--a-one-text-color)"
                    title-inactive-color="var(--a-three-text-color)" color="var(--a-main-color)" line-width="13"
                    @change="tabsChange">
                    <van-tab :title="item" v-for="item of tabsList"></van-tab>
                </van-tabs>
                <scroll-view scroll-x :scroll-left="scrollLeft" scroll-with-animation :show-scrollbar="false" enhanced
                    class="typeListScrollView">
                    <div class="typeList">
                        <div class="type_item" :class="{ active: queryData.hairType === item.templateId }"
                            v-for="item, index of hairList[activeTab]" @click="typeChange(item, index)">
                            <img :src="item?.thumImgUrl" class="typeImg" mode="aspectFill" alt="">
                            <div class="text">{{ item?.name }}</div>
                        </div>
                    </div>
                </scroll-view>

                <div class="create_btn">
                    <myDrawButton :expendNum="expendNum" @click="startFn"></myDrawButton>
                </div>
            </div>
        </div>
    </div>
    <van-toast id="van-toast" />
    <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待大于15秒钟']" @close="loadingClose">
    </newLoading>
</template>

<style lang='scss' scoped>
::v-deep {
    .van-tabs__scroll {
        background-color: transparent;
    }
}

.redrawHairstyle {
    height: 100vh;
    display: flex;
    flex-direction: column;

    .container {
        box-sizing: border-box;
        flex: 1;
        padding: 30rpx;
        display: flex;
        flex-direction: column;

        .img_box {
            flex: 1;
            border-radius: 20rpx;
            background-color: var(--a-main-box-bg-color);
            position: relative;

            .uploadImgBtn {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 228rpx;
                height: 84rpx;
                border-radius: 45rpx;
                background-color: transparent;
                border: 3rpx solid var(--a-main-color);
                color: var(--a-one-text-color);
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10rpx;
            }

            .upload_box {
                position: absolute;
                bottom: 20rpx;
                right: 20rpx;

                width: 84rpx;
                height: 84rpx;

                font-size: 16rpx;
                color: var(--a-one-text-color);
                border-radius: 13rpx;
                background: rgba(0, 0, 0, 0.6);

                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                gap: 5rpx;


                .iconfont {
                    font-size: 36rpx;
                }
            }

            .imgSty {
                width: 100%;
                height: 100%;
            }
        }
    }

    .footer {
        .footer_placeholder {
            height: 440rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 440rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 0 30rpx;

            .typeListScrollView {
                margin-top: 20rpx;

            }

            .typeList {
                width: 100%;
                display: flex;
                align-items: center;
                gap: 20rpx;

                .type_item {
                    flex-shrink: 0;
                    box-sizing: border-box;
                    width: 130rpx;
                    height: 165rpx;
                    background: var(--a-main-box-bg-color);
                    border-radius: 12rpx;
                    display: flex;
                    flex-direction: column;
                    overflow: hidden;
                    border: 3rpx solid transparent;
                    position: relative;

                    &.active {
                        color: var(--a-main-color);
                        border: 3rpx solid var(--a-main-color);
                    }

                    .typeImg {
                        width: 100%;
                        height: 100%;
                    }

                    .text {
                        position: absolute;
                        left: 0;
                        bottom: 0;
                        width: 100%;
                        height: 39rpx;
                        font-size: 21rpx;
                        color: var(--a-one-text-color);
                        text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.5);
                        background: linear-gradient(180deg, rgba(0, 0, 0, 0.1) 0%, #000000 130%);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        text-align: center;
                    }
                }
            }

            .create_btn {
                margin-top: 32rpx;
            }
        }
    }
}
</style>